import React, { Component, Fragment } from 'react'
import TodoItem from './TodoItem'
import axios from 'axios'
import './style.css'
import './mock/api'

class TodoList extends Component {
  constructor(props) {
    super(props)
    // 当组件的state或者props发生改变的时候，render函数就会重新执行
    this.state = {
      inputValue: '',
      list: []
    }
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleButtonClick = this.handleButtonClick.bind(this)
    this.handleItemDelte = this.handleItemDelte.bind(this)
  }

  render() {
    return (
      <Fragment>
        {/*注释的写法 */}
        <label htmlFor="insertArea">输入内容</label>
        <input value={this.state.inputValue}
          onChange={this.handleInputChange}
          className='input'
          id="insertArea"
          ref={(input) => { this.input = input }}
        />
        <button onClick={this.handleButtonClick}>提交</button>
        <ul ref={(ul) => { this.ul = ul }}>
          {this.getTodoItem()}
        </ul>
      </Fragment>
    )
  }
  componentDidMount() {
    axios.get('http://111111:3000/api/todolist').then((res) => {
      console.log(res)
      this.setState(() => ({
        list: [...res.data.string]
      }))
    })

  }

  getTodoItem() {
    return (
      this.state.list.map((item, index) => {
        return (
          <TodoItem
            key={index}
            content={item}
            index={index}
            deletItem={this.handleItemDelte}
          ></TodoItem>
        )
      })
    )
  }


  handleInputChange(event) {
    // this.setState({
    //   inputValue: event.target.value
    // })
    // const value = event.target.value;
    const value = this.input.value
    this.setState(() => ({
      inputValue: value
    }))
  }
  handleButtonClick() {
    // this.setState({
    //   list: [...this.state.list, this.state.inputValue],
    //   inputValue: ''
    // })
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ''
    }), () => {
      console.log(this.ul.querySelectorAll('div').length)
    })
  }
  handleItemDelte(index) {
    // immutable  : state 不允许任何改变
    // const list = [...this.state.list]
    // list.splice(index, 1)
    // this.setState({
    //   list: list
    // })
    this.setState((prevSate) => {
      const list = [...prevSate.list]
      list.splice(index, 1)
      return { list }
    })
  }
}

export default TodoList